﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Weibo4Sharp.Service;
using System.Configuration;
using Weibo4Sharp.Model;

namespace Weibo4SharpWeb.Controllers
{
    public class OAuthController : WeiboControllerBase
    {
        //
        // GET: /OAuth/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Authorize(string returnUrl)
        {
            var callback = "http://" + Request.Url.Authority + "/OAuth/AuthorizeCallback?returnUrl=" + returnUrl;
            var service = GetService();
            var requestToken = service.GetRequestToken(callback);

            Session["request_token"] = requestToken;

            var uri = service.GetAuthorizationUri(requestToken, callback);

            return new RedirectResult(uri.ToString(), false);
        }

        public ActionResult AuthorizeCallback(string oauth_token, string oauth_verifier, string returnUrl)
        {
            var requestToken = (OAuthRequestToken)Session["request_token"];

            if (requestToken == null)
            {
                throw new Exception("requestToken in session is null");
            }

            var service = GetService();
            var accessToken = service.GetAccessToken(requestToken, oauth_verifier);

            if (accessToken.TokenSecret == "?" || accessToken.Token == "?")
            {
                throw new Exception(string.Format("accessToken error t:{0} s:{1}", accessToken.Token, accessToken.TokenSecret));
            }
            
            Session["access_token"] = accessToken;             

            service = GetAuthenticatedService();

            var user = service.VerifyCredentials();

            if (user != null && user.Id != 0)
            {                              
                Session["weibo_user"] = user;

                return Redirect(returnUrl);
            }
            else
            {
                throw new Exception(string.Format("VerifyCredentials failed rsp:{0} t:{1} s:{2} v:{3}", service.Response.StatusDescription, accessToken.Token, accessToken.TokenSecret, oauth_verifier));
            }
        }
    }
}
